package com.zhang.novel.service.impl;

import com.zhang.novel.entity.OrderPay;
import com.zhang.novel.mapper.OrderPayDynamicSqlSupport;
import com.zhang.novel.mapper.OrderPayMapper;
import com.zhang.novel.service.OrderService;
import com.zhang.novel.service.UserService;
import lombok.RequiredArgsConstructor;
import org.mybatis.dynamic.sql.render.RenderingStrategies;
import org.mybatis.dynamic.sql.select.render.SelectStatementProvider;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import static com.zhang.novel.mapper.OrderPayDynamicSqlSupport.*;
import static org.mybatis.dynamic.sql.SqlBuilder.isEqualTo;
import static org.mybatis.dynamic.sql.select.SelectDSL.select;

@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final OrderPayMapper orderPayMapper;

    private final UserService userService;

    @Override
    public Long createPayOrder(Byte payChannel, Integer payAmount, Long userId) {
        Date currentDate = new Date();
        Long outTradeNo = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(currentDate)+new Random().nextInt(10));
        OrderPay orderPay = new OrderPay();
        orderPay.setOutTradeNo(outTradeNo);
        orderPay.setPayChannel(payChannel);
        orderPay.setTotalAmount(payAmount);
        orderPay.setUserId(userId);
        orderPay.setCreateTime(currentDate);
        orderPay.setUpdateTime(currentDate);
        orderPayMapper.insertSelective(orderPay);
        return outTradeNo;
    }

    @Override
    public void updatePayOrder(Long outTradeNo, String tradeNo, String tradeStatus) {
        SelectStatementProvider selectStatementProvider = select(id, payStatus, totalAmount, userId)
                .from(orderPay)
                .where(OrderPayDynamicSqlSupport.outTradeNo, isEqualTo(outTradeNo))
                .build()
                .render(RenderingStrategies.MYBATIS3);
        OrderPay orderPay = orderPayMapper.selectMany(selectStatementProvider).get(0);

        // 判断订单
        if(orderPay.getPayStatus()!=1){
            // 说明订单为处理
            if("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)){
                // 支付成功
                // 1. 更新订单状态为成功
                orderPay.setPayStatus((byte) 1);
                orderPay.setUpdateTime(new Date());
                orderPayMapper.updateByPrimaryKeySelective(orderPay);

                // 2.增加用户余额
                userService.addAmount(orderPay.getUserId(),orderPay.getTotalAmount()*100);
            }
        }
    }
}
